package messagesvc.websocket.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.ucloud.microsf.messagesvc.websocket.model.ChatMessage;
import cn.ucloud.microsf.messagesvc.websocket.service.WsSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Slf4j
@Component
public class MessageHandler extends AbstractWebSocketHandler {

  /**
   * 建立成功事件
   */
  @Override
  public void afterConnectionEstablished(WebSocketSession session) {
    WsSession.add(session);
    WsSession.readCacheAndSend(WsSession.getToken(session));
  }

  /**
   * 断开连接时
   */
  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
    WsSession.remove(session);
  }

  /**
   * 接收文本消息
   */
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    // 获得客户端传来的消息
    String request = message.getPayload();
    //    String token = WsSession.getToken(session);
    //    String resp = String.format("【%s】你好，已收到消息：%s [%s]", token, request, DateUtil.formatDateTime(new Date()));
    //    log.info("收到客户端【{}】发送的文本消息: {} >>> 服务端回复：{}", token, request, resp);
    //    session.sendMessage(new TextMessage(resp));
    sendToOtherIfNeed(request);
  }

  /**
   * 接收二进制消息
   */
  @Override
  protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
    // 获得客户端传来的消息
    //    ByteBuffer payload = message.getPayload();
    //    int length = message.getPayloadLength();
    //    String token = WsSession.getToken(session);
    //    String resp = String.format("【%s】你好，已收到消息：文件大小 [%s] [%s]", token, length, DateUtil.formatDateTime(new Date()));
    //    log.info("收到客户端【{}】发送的二进制消息 >>> 服务端回复：{}", token, resp);
    //    session.sendMessage(new TextMessage(resp));
  }

  private void sendToOtherIfNeed(String request) {
    if (StrUtil.isNotBlank(request)) {
      ChatMessage message = JSONUtil.toBean(request, ChatMessage.class);
      if (StrUtil.isNotBlank(message.getMContent())
          && StrUtil.isNotBlank(message.getMToken())) {
        WsSession.getAndSend(message.getMToken(), message.getMContent());
      }
    }

  }

}
